$('document').ready(function() {
    $('#delete-multiple-items').click(function() {
        $('#delete-multiple-items-form').submit();
    });

    $('#search-item').click(function() {
        $('#search-bar').fadeIn(400, function() {
            $('#search-box-input').focus();
        });
    });

    $('#search-box-input').focusout(function() {
        $('#search-bar').fadeOut();
    });

    $('#search-box-input').keypress(function(e) {
        if (e.which === 13) {
            window.top.location = '/items?q='+$(this).val();
        }
    });
    
    $('.item-check-input').change(function() {
        if (this.checked == true) {
            $(this).parent().css('background-color', '#c02835');
        } else {
            $(this).parent().css('background-color', '#ffe3e2');
        }
    });
    
});

function view_item(url) {
    window.open(url, '', 'width=600,height=600');
}

function displayGenericErrorNotification() {
	$(document).ready(function() {
		jError("L'action n'a pas pu &ecirc;tre effectu&eacute;e. S'il vous pla&icirc;t essayer de nouveau.", {
				autoHide: true,
				clickOverlay: true,
				TimeShown: 2000,
				HorizontalPosition: 'center',
				VerticalPosition: 'center',
				onCompleted: function() {
				}
			}
		);
	});
}

function collectFormData(fields) {
	var data = {};
	for (var i = 0; i < fields.length; i++) {
		var $item = $(fields[i]);
		data[$item.attr('name')] = $item.val();
	}
	return data;
}

function processAddEditForm(addEditValidationUrl, performAddEditUrl) {
	$(document).ready(function() {
		var $form = $('#add-edit-form');
		$form.bind('submit', function(e) {
			// AJAX validation
			var $formElements = $form.find('input[type!=radio], select, textarea');
			var formElementsData = collectFormData($formElements);
			formElementsData["type"] = $('input[name=type]:radio:checked').val();
			$.post(addEditValidationUrl, formElementsData, function(response) {
				$form.find('.help-inline').empty();
				if (response.status == 'FAILURE') {
					for (var i = 0; i < response.errorMessageList.length; i++) {
						var item = response.errorMessageList[i];
						var $controlGroup = $('#' + item.fieldName + "ControlGroup");
						$controlGroup.find('.help-inline').html(item.message);
					}
				} else {
					performAddEdit(performAddEditUrl, formElementsData, $form);
				}
			}, 'json');
			e.preventDefault();
			return false;
		});
	});
}

function performAddEdit(performAddEditUrl, parameters, $form) {
	$(document).ready(function() {
	    $.ajax({
	        type: 'POST',
	        url:  performAddEditUrl,
	        data: parameters,
	        dataType: 'json',
	        async: true,
	        success: function(result) {
	        	if (result.status == 'SUCCESS') {
	        		$form.unbind('submit');
					$form.submit();
	        	}
	        	else {
	        		displayGenericErrorNotification();
	        	}
	        },
	        error: function(jqXHR, textStatus, errorThrown) {
	        	displayGenericErrorNotification();
	        }
	    });
	});
}

function collectCheckboxData(fields) {
	var data = "";
	if (fields.length > 0) {
		for (var i = 0; i < fields.length; i++) {
			var $item = $(fields[i]);
			if (i == fields.length - 1) {
				data = data.concat($item.val());
			}
			else {
				data = data.concat($item.val()).concat("_");
			}
		}
	}
	return data;
}

function performDelete(deleteUrl) {
	$(document).ready(function() {
		var $checkboxes = $('input:checkbox:checked');
		var checkboxesData = collectCheckboxData($checkboxes);
	    window.location = deleteUrl + "?ids=" + checkboxesData;
	});
}
